//
//  XNNormalTableViewCell.m
//  XINNingOA
//
//  Created by samuel on 2021/7/12.
//

#import "XNNormalTableViewCell.h"
#import "XNFileModel.h"
#import <QuickLook/QuickLook.h>
#import "YTKNetworkConfig.h"
#import "YTKNetworkAgent.h"
#import "AFURLSessionManager.h"
#import "XNUtil.h"
#import "XNImageCollectionViewCell.h"
#import "SVProgressHUD.h"
#import "GKPhotoBrowser.h"

@interface XNNormalTableViewCell()<QLPreviewControllerDataSource,UICollectionViewDelegate,UICollectionViewDataSource>

@property (nonatomic, strong) NSMutableArray *infoViewArray;

@property (nonatomic, weak) UIView *containView;

@property (nonatomic, weak) UIImageView *image;

@property (nonatomic, strong) QLPreviewController *previewController;

@property (nonatomic, copy) NSURL *fileURL;



@end

@implementation XNNormalTableViewCell


+ (instancetype)tabelViewCellWithTableView:(UITableView *)tableView
                                  ForIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellID = @"XNNormalTableViewCellID";
    XNNormalTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellID];
    if (cell == nil) {
        cell = [[XNNormalTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellID];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    return cell;
}

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier{
    if (self == [super initWithStyle:style reuseIdentifier:reuseIdentifier]) {
        self.infoViewArray = [NSMutableArray array];
        self.contentView.backgroundColor = [UIColor colorWithHexString:@"#F8F8F8"];
        UIView *contentView = [[UIView alloc] init];
        contentView.backgroundColor = [UIColor whiteColor];
        contentView.layer.cornerRadius = 10;
        contentView.clipsToBounds = YES;
        [self.contentView addSubview:contentView];
        self.containView = contentView;
        [contentView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(self.contentView).offset(8);
            make.bottom.equalTo(self.contentView).offset(-8);
            make.left.equalTo(self.contentView).offset(16);
            make.right.equalTo(self.contentView).offset(-16);
        }];
        
        UIImageView *image = [[UIImageView alloc] init];
        image.image = [UIImage imageNamed:@"overout"];
        [self.contentView addSubview:image];
        self.image = image;
        [image mas_makeConstraints:^(MASConstraintMaker *make) {
            make.right.equalTo(contentView).offset(-30);
            make.centerY.equalTo(contentView);
            make.size.mas_equalTo(CGSizeMake(60, 60));
        }];
    }
    return self;
}

- (void)setItemModel:(XNShowItemModel *)itemModel
{
    _itemModel = itemModel;
    self.image.hidden = !itemModel.showOverImage;
    [self.infoViewArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        [obj removeFromSuperview];
    }];
    [self.infoViewArray removeAllObjects];
    
    __block BOOL showFile = NO;
    if (itemModel.fileArray.count > 0) {
        showFile = YES;
    }
    
    __block UILabel *lastLab;
    [itemModel.showItemArray enumerateObjectsUsingBlock:^(NSString *obj, NSUInteger idx, BOOL * _Nonnull stop) {
        UILabel *lab = [[UILabel alloc] init];
        lab.font = [UIFont systemFontOfSize:12];
        lab.text = obj;
        lab.numberOfLines = 0;
        [self.containView addSubview:lab];
        [lab mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.equalTo(self.containView).offset(10);
            if (idx == 0) {
                make.top.equalTo(self.containView).offset(10);
            }else{
                make.top.equalTo(lastLab.mas_bottom).offset(5);
            }
            make.right.equalTo(self.containView).offset(-10);
            if (idx == itemModel.showItemArray.count - 1 && !showFile) {
                make.bottom.equalTo(self.containView).offset(-10);
            }
        }];
        lastLab = lab;
        [self.infoViewArray addObject:lab];
    }];
    
    if (showFile) {
        if (itemModel.fileIsImage) {
            UICollectionViewFlowLayout *flowLayout1 =[[UICollectionViewFlowLayout alloc]init];
            flowLayout1.itemSize = CGSizeMake(90,90);
            flowLayout1.sectionInset = UIEdgeInsetsMake(0, 9, 0, 10);
            flowLayout1.minimumLineSpacing = 10;
            flowLayout1.minimumInteritemSpacing = 0;
            [flowLayout1 setScrollDirection:UICollectionViewScrollDirectionHorizontal];
            UICollectionView *collectView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:flowLayout1];
            collectView.showsVerticalScrollIndicator = NO;
            collectView.showsHorizontalScrollIndicator = NO;
            [collectView registerClass:[XNImageCollectionViewCell class] forCellWithReuseIdentifier:@"XNImageCollectionViewCellID"];
            collectView.backgroundColor = [UIColor whiteColor];
            collectView.delegate = self;
            collectView.dataSource = self;
            [self.containView addSubview:collectView];
            [collectView mas_makeConstraints:^(MASConstraintMaker *make) {
                make.top.equalTo(lastLab.mas_bottom).offset(5);
                make.left.equalTo(self.containView).offset(10);
                make.right.equalTo(self.containView).offset(-10);
                make.height.mas_equalTo(100);
                make.bottom.equalTo(self.containView).offset(-10);
            }];
            [self.infoViewArray addObject:collectView];
        }else{
            __block UIButton *lastBtn;
            [itemModel.fileArray enumerateObjectsUsingBlock:^(XNFileModel *obj, NSUInteger idx, BOOL * _Nonnull stop) {
                UIButton *btn = [[UIButton alloc] init];
                [btn setTitleColor:[UIColor colorWithHexString:@"#358AFF"] forState:UIControlStateNormal];
                btn.titleLabel.font = [UIFont systemFontOfSize:12];
                btn.tag = idx;
                [btn setTitle:obj.fileName forState:UIControlStateNormal];
                [btn addTarget:self action:@selector(showFileDetail:) forControlEvents:UIControlEventTouchUpInside];
                [self.contentView addSubview:btn];
                [btn mas_makeConstraints:^(MASConstraintMaker *make) {
                    make.left.equalTo(self.containView).offset(10);
                    if (idx == 0) {
                        make.top.equalTo(lastLab.mas_bottom);
                    }else{
                        make.top.equalTo(lastBtn.mas_bottom).offset(5);
                    }
                    make.height.mas_equalTo(20);
                    make.right.equalTo(self.containView).offset(-10);
                    if (idx == itemModel.fileArray.count - 1) {
                        make.bottom.equalTo(self.containView).offset(-10);
                    }
                }];
                lastBtn = btn;
                [self.infoViewArray addObject:btn];
            }];
        }
    }
    
}

- (void)showFileDetail:(UIButton *)btn
{
    self.previewController = [[QLPreviewController alloc] init];
    self.previewController.dataSource = self;
    XNFileModel *fileModel = self.itemModel.fileArray[btn.tag];
    NSLog(@"%@",fileModel.fileName);
    
    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
    
    AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
    NSString *urlStr = [NSString stringWithFormat:@"%@/%@",[YTKNetworkConfig sharedConfig].baseUrl,fileModel.fileUrl];
    NSString *fileName = [urlStr lastPathComponent]; //获取文件名称
    NSURL *URL = [NSURL URLWithString:urlStr];
    self.previewController.title = fileName;
    NSURLRequest *request = [NSURLRequest requestWithURL:URL];
    
    //判断是否存在
    if ([self isFileExist:fileName]) {
        NSURL *documentsDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];
        NSURL *url = [documentsDirectoryURL URLByAppendingPathComponent:fileName];
        self.fileURL = url;
        UIViewController *currentVC = [XNUtil parentControllerFromView:self];
        [currentVC presentViewController:self.previewController animated:YES completion:nil];
        //刷新界面,如果不刷新的话，不重新走一遍代理方法，返回的url还是上一次的url
        [self.previewController refreshCurrentPreviewItem];
    } else {
        [SVProgressHUD show];
        NSURLSessionDownloadTask *downloadTask = [manager downloadTaskWithRequest:request progress:^(NSProgress *downloadProgress){
            
        } destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
            NSURL *documentsDirectoryURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:NO error:nil];
            NSURL *url = [documentsDirectoryURL URLByAppendingPathComponent:fileName];
            return url;
        } completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {
            [SVProgressHUD dismiss];
            self.fileURL = filePath;
            UIViewController *currentVC = [XNUtil parentControllerFromView:self];
            [currentVC presentViewController:self.previewController animated:YES completion:nil];
            //刷新界面,如果不刷新的话，不重新走一遍代理方法，返回的url还是上一次的url
            [self.previewController refreshCurrentPreviewItem];
        }];
        [downloadTask resume];
    }
    
}

- (BOOL)isFileExist:(NSString *)fileName
{
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *path = [paths objectAtIndex:0];
    NSString *filePath = [path stringByAppendingPathComponent:fileName];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL result = [fileManager fileExistsAtPath:filePath];
    return result;
}

- (id<QLPreviewItem>)previewController:(QLPreviewController *)controller previewItemAtIndex:(NSInteger)index {
    return self.fileURL;
}

/// 文件数
- (NSInteger)numberOfPreviewItemsInPreviewController:(QLPreviewController *)controller {
    return 1;
}


- (NSInteger) numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return  1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView
     numberOfItemsInSection:(NSInteger)section {

    return self.itemModel.fileArray.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView
                  cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *cellID = @"XNImageCollectionViewCellID";
    XNImageCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellID forIndexPath:indexPath];
    cell.fileModel = self.itemModel.fileArray[indexPath.row];
    return cell;

}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    NSMutableArray *array = [NSMutableArray array];
    [self.itemModel.fileArray enumerateObjectsUsingBlock:^(XNFileModel *obj, NSUInteger idx, BOOL * _Nonnull stop) {
        GKPhoto *photo = [GKPhoto new];
        photo.url = [NSURL URLWithString:[NSString stringWithFormat:@"%@/%@",[YTKNetworkConfig sharedConfig].baseUrl,obj.fileUrl]];
        [array addObject:photo];
    }];
    
//    XNFileModel *fileModel = self.itemModel.fileArray[indexPath.row];

    GKPhotoBrowser *browser = [GKPhotoBrowser photoBrowserWithPhotos:[NSArray arrayWithArray:array] currentIndex:indexPath.row];
    browser.showStyle = GKPhotoBrowserShowStyleNone;
    [browser showFromVC:[XNUtil parentControllerFromView:self]];
}

@end
